﻿namespace Gol.Domain
{
    public class GameOfLife
    {
        public GameOfLife(int rows, int cols)
        {
            CellGrid = new CellGrid(rows,cols);
        }

        public CellGrid CellGrid { get; private set; }

        


        public void Start(int[,] lifeOnes)
        {
            CellGrid.Intialize(lifeOnes);
        }

        public void NextGeneration()
        {
            var newGrid = new CellGrid(CellGrid.NumberOfRows, CellGrid.NumberOfColums);

            for (int i = 0; i < CellGrid.NumberOfRows; i++)
            {
                for (int j = 0; j < CellGrid.NumberOfColums; j++)
                {
                    var numberOfneighbours = CellGrid.CalculateNumberOfNeighboursForCell(i, j);
                    if (this.CellGrid[i, j].IsAlive)
                    {
                        if (numberOfneighbours == 0 || numberOfneighbours == 1)
                        {
                            newGrid[i, j].IsAlive = false;
                        }
                        if (numberOfneighbours == 2 || numberOfneighbours == 3)
                        {
                            newGrid[i, j].IsAlive = true;
                        }

                        if (numberOfneighbours >= 4)
                        {
                            newGrid[i, j].IsAlive = false;
                        }
                    }
                    else
                    {
                        if (numberOfneighbours == 3)
                        {
                            newGrid[i, j].IsAlive = true;
                        }
                    }

                }
            }

            for (int i = 0; i < CellGrid.NumberOfRows; i++)
            {
                for (int j = 0; j < CellGrid.NumberOfColums; j++)
                {
                    CellGrid[i, j].IsAlive = newGrid[i, j].IsAlive;
                }
            }
        }
    }
}